import logging

from openlbsserver.lib.base import *

from openlbsserver.model import meta
from openlbsserver.model import User

log = logging.getLogger(__name__)

class UserControllerController(BaseController):
    def login_get(self):
        return render('index')

    def logout(self):
        try:
            session.clear()
            session.save()
        except:
            pass
            
        h.redirect_to('/')

    def login(self):
        try:
            # authenticate
            try:
                user = meta.Session.query(User).filter_by(username=request.POST['username']).one()
                if not h.auth(user, request.POST['password']):
                    c.error = True
                    return render('index')
            except:
                # invalid username
                c.error = True
                return render('index')
                
            session['user_id'] = user.id
            session.save()
            
            
            
            
        except:
            abort(404)
            
        h.redirect_to('/')